from pydantic import BaseModel, EmailStr, Field, field_validator
from typing import Optional


class UserBase(BaseModel):
    """
    用户基础模型（用于公共字段）
    """

    username: str = Field(..., min_length=3, max_length=50, example="alice")
    email: Optional[EmailStr] = Field(
        None, example="user@example.com", description="必须是有效的邮箱格式"
    )


class UserCreate(UserBase):
    """
    用户创建模型（包含密码）
    """

    password: str = Field(
        ...,
        min_length=8,
        max_length=100,
        description="至少8个字符",
        example="securePassword123!",
    )

    @field_validator("password")
    def password_complexity(cls, v):
        """添加自定义密码校验"""
        if not any(c.isupper() for c in v):
            raise ValueError("密码必须包含至少一个大写字母")
        if not any(c.isdigit() for c in v):
            raise ValueError("密码必须包含至少一个数字")
        return v


class UserResponse(UserBase):
    """
    用户响应模型（不包含敏感信息）
    """

    id: int = Field(..., example=1)
    is_active: bool = Field(True, example=True)

    class Config:
        from_attributes = True
        json_schema_extra = {
            "example": {
                "id": 1,
                "username": "alice",
                "email": "alice@example.com",
                "is_active": True,
            }
        }


class Token(BaseModel):
    access_token: str
    token_type: str = "bearer"


class UpdateUser(BaseModel):
    """用户更新模型"""

    username: str = Field(default="")
    email: str = Field(default="")
    password: str = Field(default="")
    is_active: bool = Field(default=True)
    is_superuser: bool = Field(default=False)


class RegisterUser(BaseModel):
    username: str = Field(..., min_length=3, max_length=50, example="alice")
    email: Optional[EmailStr] = Field(
        None, example="user@example.com", description="必须是有效的邮箱格式"
    )
    password: str = Field(
        ...,
        min_length=8,
        max_length=100,
        description="至少8个字符",
        example="securePassword123!",
    )
    check_pwd: str = Field(
        ...,
        min_length=8,
        max_length=100,
        description="至少8个字符",
        example="securePassword123!",
    )
    
    @field_validator("password")
    def password_complexity(cls, v):
        """添加自定义密码校验"""
        if not any(c.isupper() for c in v):
            raise ValueError("密码必须包含至少一个大写字母")
        if not any(c.isdigit() for c in v):
            raise ValueError("密码必须包含至少一个数字")
        return v